package user.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;

import commons.PageResult;
import commons.SmsrepaymentUtils;
import commons.SmsUtils;
import entity.CcmsBankcard;
import entity.CcmsBill;
import entity.CcmsCredit;
import entity.CcmsRepayment;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;
import user.service.IBankcardService;
import user.service.IBillService;
import user.service.ICredit;
import user.service.IRepaymentService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/repayment")
public class CcmsRepayController {

    @Autowired
    IRepaymentService iRepaymentService;
    @Autowired
    IBillService iBillService;
    @Autowired
    IBankcardService iBankcardService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ICredit iCredit;
    @ApiIgnore
    @RequestMapping("go")
    public String go(){
        return "repaymentdetil";
    }
    @ApiIgnore
    @RequestMapping("/repaymentmenu")
    public String repaymentmenu(Model model, HttpServletRequest request){
        Integer userId = Integer.valueOf((String)request.getSession().getAttribute("userid"));
        List<CcmsCredit> myCredits = iCredit.getMyCredit(userId);
        model.addAttribute("myCredits",myCredits);
        return "repaymentmenu";
    }
    @ApiIgnore
    @RequestMapping("/gobill")
    public String gobill(Long cardnum,HttpServletRequest request ){
        CcmsCredit credit = iCredit.getCredit(cardnum,request);
        return "gobill";
    }
    @ApiOperation(value = "分页查询当前用户所有还款记录,需登录后取到session中的userid")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex",value = "当前页",required = true,dataType = "int"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "int")
    })
    @ResponseBody
    @PostMapping("list")
    public PageResult getAllRepayment(int pageIndex, int pageSize,HttpServletRequest request){
        String userId =  (String) request.getSession().getAttribute("userid");
            PageResult pageBean= iRepaymentService.getpage(pageIndex,pageSize,userId);
        return pageBean;
    }

    @ApiOperation(value = "跳到还款页面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "billid",value = "账单id",required = true,dataType = "int"),
    })
    @GetMapping("repayment")
    public String getbill(int billid,Model model,HttpServletRequest request){
      CcmsBill bill = iBillService.getbillByPrimaryKey(billid);
        List<CcmsBankcard> allBankcard = iBankcardService.getAllBankcard();
        Integer creditId = bill.getCreditId();
        CcmsCredit credit = iCredit.getCreditById(creditId);
        model.addAttribute("credit",credit);
        model.addAttribute("allBankcard",allBankcard);
        model.addAttribute("bill",bill);
        return "repayment";
    }

    //发送验证码
    @ApiOperation(value = "发送验证码,返回随机验证码代表代表成功,返回空代表发送失败")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phonenum",value = "电话号码",required = true,dataType = "String"),
    })
    @ResponseBody
    @GetMapping("code")
    public String getcode(String phonenum){
//        SmsrepaymentUtils smsrepaymentUtils = new SmsrepaymentUtils();
//        int m=0;
//        SendSmsResponse sendSmsResponse=null;
//        try {
            String code =(int)(Math.random()*1000000)+""; //随机产生一个 6 位数；
            redisTemplate.opsForValue().set("code"+phonenum+code,code,290,TimeUnit.SECONDS);
//            sendSmsResponse = smsrepaymentUtils .sendSms(phonenum,code,"SMS_204297250");
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
//
//        if (sendSmsResponse.getCode()!=null&& sendSmsResponse.getCode().equals("OK")){
//            m=1;
//        }
//        return m;
        return code;
    }
    //验证验证码
    @ApiOperation(value = "验证用户输入验证码,返回0代表验证失败,1代表验证成功")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code",value = "用户输入验证码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "phonenum",value = "电话号码",required = true,dataType = "String")
    })
    @ResponseBody
    @GetMapping("checkcode")
    public int checkcode(String code,String phonenum){
        int m=0;
        String checkcode = (String) redisTemplate.opsForValue().get("code"+phonenum+code);
        if (checkcode!=null){
            m=1;
        }
        return m;
    }
//验证密码
@ApiOperation(value = "验证用户输入密码,返回0代表验证失败,1代表验证成功")
@ApiImplicitParams({
        @ApiImplicitParam(name = "bankcardnum",value = "银行卡号:9583298723322322384,9895847509585748376,9889455464656456456 密码:123456",required = true,dataType = "String"),
        @ApiImplicitParam(name = "password",value = "用户输入密码",required = true,dataType = "String")
})
    @ResponseBody
    @GetMapping("password")
    public int checkpassword(String bankcardnum,String password){
        int m=0;
            CcmsBankcard bankcard=iBankcardService.getBankcard(bankcardnum);
        if (bankcard!=null&&password!=null){
            if (bankcard.getPassword().equals(password)){
                m=1;
            }
        }
        return m;
    }
    //银行卡扣款,修改账单

    @ApiOperation(value = "银行卡扣款,并修改账单状态,返回1代表异常,0代表成功,2代表银行卡余额不足")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "money",value = "还款金额",required = true,dataType = "BigDecimal"),
            @ApiImplicitParam(name = "bankcardnum",value = "银行卡号:9583298723322322384,9895847509585748376,9889455464656456456 ",required = true,dataType = "String"),
            @ApiImplicitParam(name = "billId",value = "账单id",required = true,dataType = "Int")
    })
    @ResponseBody
    @GetMapping("deduct")
    public int deductmoney(BigDecimal money,String bankcardnum,Integer billId){
        int m=1;//1代表发生异常
        CcmsBankcard bankcard=iBankcardService.getBankcard(bankcardnum);
        if (bankcard!=null){
            if (bankcard.getBalance().compareTo(money)!=-1){
           BigDecimal newmoney= bankcard.getBalance().subtract(money);
           bankcard.setBalance(newmoney);
           int n =  iBankcardService.deductmoney(bankcard);
           if (n>0){
              int i = iBillService.updateBill(billId,money);  //还款后修改账单
              if (i>0){
                  m=0;//m=0代表转账成功
                  CcmsBill bill = iBillService.getbillByPrimaryKey(billId);
                  CcmsCredit credit = iCredit.getCreditById(bill.getCreditId());
                  if (credit.getDebt().compareTo(money)!=-1){
                      BigDecimal debt= credit.getDebt().subtract(money);
                      credit.setDebt(debt);
                      int j= iCredit.updatedebt(credit);
                  }
              }
           }
            }else {
                m=2;//2代表银行卡余额不足
            }
        }
        return m;
    }

    //跳转到还款结果页面
    @ApiIgnore
    @ApiOperation(value = "跳转到还款结果页面,并将付款结果插入数据库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data",value = "0,页面提示成功,1,页面提示异常",required = true,dataType = "String"),
            @ApiImplicitParam(name = "repayment",value = "还款结果对象",required = true,dataType = "CcmsRepayment"),
            @ApiImplicitParam(name = "newbalance",value = "应付款金额,填数字,需大于实际付款金额",required = true,dataType = "String"),
            @ApiImplicitParam(name = "repaymentmoney",value = "实际付款金额,填数字",required = true,dataType = "String"),
            @ApiImplicitParam(name = "billId",value = "账单id",required = true,dataType = "Int")
    })
    @ResponseBody
    @RequestMapping("result")
    public ModelAndView toresult(String data, CcmsRepayment repayment, String newbalance, String repaymentmoney, Integer billId, HttpServletRequest request){
        BigDecimal newBalance=null;
        BigDecimal rmoney=null;
        if (newbalance!=null&&!newbalance.equals("")){
            String balance = newbalance.replaceAll(",", "");//去除千分位的逗号
            newBalance=new BigDecimal(balance);//字符串转为BigDecimal类型
        }
       if (repaymentmoney!=null&&!repaymentmoney.equals("")){
           String money = repaymentmoney.replaceAll(",", "");
           rmoney =new BigDecimal(money);
       }
       repayment.setBillId(billId);
        repayment.setNewBalance(newBalance);//将本期应付金额赋值给对象
        repayment.setRepayment(rmoney);//将本期付款金额赋值给对象
        Date date = new Date();//获得系统时间.
        SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
        Date time=null;
        String nowTime = sdf.format(date);
        try {
            time = sdf.parse(nowTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        repayment.setRepaymentDate(time);
        String userid = (String) request.getSession().getAttribute("userid");
        Integer userId=Integer.parseInt(userid );
        repayment.setUserId(userId);
        String result=null;
        if (data!=null){
            int data1= Integer.parseInt(data);
            if (data1==1){
                result="发生未知异常,转账失败!请联系客服9558";
            }else if (data1==0){
                repayment.setRepaymentState("已还款");
                int n = iRepaymentService.addRepayment(repayment);//将付款结果插入数据库
                result="还款成功!";
            }
        }
        return new ModelAndView("/result","result",result);
    }

}
